--!native
RStorage = game.ReplicatedStorage;
local sharedLibs = RStorage.SharedLibs;
local pt = require(sharedLibs.Prototype);

--[[
    定义Vec2类型. 注意: 这个Vec2和系统的Vector2一定程度上兼容.
]]
local Vec2 = pt.proto();

-- 创建新的Vec2对象
function Vec2:constructor(x, y)
    self.x = x or 0
    self.y = y or 0
end

-- 将Vec2转换为字符串
function Vec2:tostring()
    return string.format("(%f, %f)", self.x, self.y)
end

-- 将Vec2相加
function Vec2:Add(other)
    return Vec2.new(
        self.x + other.x,
        self.y + other.y)
end

-- 将Vec2相减
function Vec2:Sub(other)
    return Vec2.new(
        self.x - other.x,
        self.y - other.y)
end

-- 将Vec2相乘
function Vec2:Mul(other)
    if type(other) == "number" then
        return Vec2.new(
            self.x * other,
            self.y * other)
    elseif type(other) == "table" and other.__name == "Mat2" then
		local v = Vec2.new(
					other[1] * self.x + other[2] * self.y,
					other[3] * self.x + other[4] * self.y);
        return v;
    else
        error("unsupported operand types for Vec2 multiplication")
    end
end

-- 将Vec2取负
function Vec2:Invert()
    return Vec2.new(
        -self.x, -self.y)
end

-- 比较两个Vec2是否相等
function Vec2:Equal(other)
    return self.x == other.x and
           self.y == other.y
end

-- 计算Vec2的长度
function Vec2:Length()
    return math.sqrt(self.x * self.x + self.y * self.y)
end

-- 返回当前向量的单位向量
function Vec2:Unit()
    local len = self:Length()
    if len == 0 then
        error("cannot normalize zero-length vector")
    end
    return Vec2.new(
        self.x / len,
        self.y / len)
end

-- 将当前向量单位化
function Vec2:Normalize()
    local len = self:Length()
    if len == 0 then
        error("cannot normalize zero-length vector")
    end
    self.x = self.x / len;
	self.y = self.y / len;
	return self;
end

-- 创建零向量
function Vec2.Zero()
    return Vec2.new(0, 0)
end

return Vec2;

